package cn.wolfcode.core;

import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/{token}")
@Component
@Slf4j
public class WebSocketServer {

    public static final Map<String,Session> SESSION_MAP = new ConcurrentHashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("token") String token) {
        log.info("[WebSocket服务] 有新的客户端连接上来了 {}", token);
        SESSION_MAP.put(token,session);
    }

    @OnClose
    public void onClose(@PathParam("token") String token){
        log.info("[WebSocket服务] 连接准备关闭 {}",token);
        SESSION_MAP.remove(token);
    }

    @OnError
    public void onError(Throwable throwable){
        log.warn("[WebSocket服务] 客户端连接异常 {}",throwable);
    }
}
